﻿using System.Collections.Generic;
using System.Linq;
using DataAccess.Entities;
using DataAccess.Repositories;
using NHibernate;
using NHibernate.Criterion;

namespace Zeenck.DataAccess.Repositories
{
    public class GenderRepository : IRepository<Gender>
    {
        #region IRepository<Gender> Members

        void IRepository<Gender>.Save(Gender entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(entity);
                    transaction.Commit();
                }
            }
        }

        void IRepository<Gender>.Update(Gender entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Update(entity);
                    transaction.Commit();
                }
            }
        }

        void IRepository<Gender>.Delete(int id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(id);
                    transaction.Commit();
                }
            }
        }

        Gender IRepository<Gender>.GetById(int id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.CreateCriteria<Gender>().Add(Restrictions.Eq("Id", id)).UniqueResult<Gender>();
        }

        IList<Gender> IRepository<Gender>.GetAll()
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.CreateCriteria<Gender>().List<Gender>();
        }

        public IList<Gender> Find(string searchText, int maxResults)
        {
            IList<Gender> interests;
            using (ISession session = NHibernateHelper.OpenSession())
                interests = session.CreateCriteria<Gender>().List<Gender>();

            var result = from n in interests
                         where n.Type.Contains(searchText)
                         orderby n.Type
                         select n;

            return result.Take(maxResults).ToList();
        }

        #endregion
    }
}